<?php

namespace App\Listeners;

use App\Events\ActivityStarted;
use App\Models\Activity\Activity;
use Illuminate\Container\Container;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\App;

class RefreshRedis
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ActivityStarted  $event
     * @return void
     */
    public function handle(ActivityStarted $event)
    {
        $activity = Activity::query()->where('id', $event->activityId)->first();

        $limit = json_decode($activity->getAttribute('limit'));
        $allow = $limit->num;
        $maxVote = isset($limit->votes) ? $limit->votes : 0;
        $mode = $limit->type == 'day' ? 1 : 2;
        $start = strtotime($activity->getAttribute('startTime'));
        $end = strtotime($activity->getAttribute('endTime'));

        $redis = Container::getInstance()->make('redis');

        $redis->hmset(
            sprintf('rule:%s', $activity->getAttribute('id')),
            'allow_votes',
            $allow,
            'brush_mode',
            $mode,
            'start',
            $start,
            'end',
            $end,
            'is_pause',
            0,
            'max_votes',
            $maxVote
        );

        $redis->hmset(
            sprintf('rules:%s', $activity->id),
            'limit',
            $limit->num,
            'type',
            $limit->type,
            'start_at',
            strtotime($activity->getAttribute('startTime')),
            'end_at',
            strtotime($activity->getAttribute('endTime')),
            'pause',
            $activity->getAttribute('isPause'),
            'max_votes',
            $maxVote
        );
    }
}
